package com.dmall.chapter05.section06;

import com.dmall.chapter02.section09.Graph;

import java.util.LinkedList;
import java.util.Queue;

public class CircleDetection {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private boolean hasCircle = false;

    public CircleDetection(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        for (int i = 0; i < pre.length; i++) {
            pre[i] = -1;
        }

        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                if (bfs(v)) {
                    hasCircle = true;
                    break;
                }
            }
        }
    }

    private boolean bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        pre[s] = s;
        while (!queue.isEmpty()) {
            Integer v = queue.remove();
            for (int w : G.adj(v)) {
                if (!visited[w]) {
                    visited[w] = true;
                    pre[w] = v;
                    queue.add(w);
                } else if (pre[v] != w) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean hasCircle() {
        return hasCircle;
    }

    public static void main(String[] args) {
        String filename = CircleDetection.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CircleDetection circleDetection = new CircleDetection(g);
        System.out.println(circleDetection.hasCircle());

        String filename2 = CircleDetection.class.getClassLoader().getResource("g2.txt").getPath();
        Graph g2 = new Graph(filename2);
        CircleDetection circleDetection2 = new CircleDetection(g2);
        System.out.println(circleDetection2.hasCircle());
    }
}
